import { Box, Icon, useCall, useFieldCtx, useFormValue, useSimpleMemo } from '@/components';
import { INPUT_KEYS } from '@/constants/componentKeys';
import { SelectProduct } from '@/pages/components';
import { forkHandler, pick } from '@/utils';
import { Input } from 'antd';
import clsx from 'clsx';
import React from 'react';

function ExemptionsSelect({ value, onClick, onChange, onOk, ...rest }) {
  const [inputProps, otherProps] = useSimpleMemo(pick(rest, INPUT_KEYS));

  const form = useFieldCtx('form');
  const companyCode = useFormValue(form, ['productAddVo', 'productAttrVo', 'companyCode']);
  const productCode = useFormValue(form, ['productAddVo', 'productAttrVo', 'productCode']);

  console.log({ companyCode, productCode });

  const handleOk = useCall((selected) => {
    const codes = selected?.map((v) => v.businessCode).join(',') ?? '';
    onChange?.(codes);
  });

  const handleClick = useCall(forkHandler(onClick, () => !inputProps.disabled, true));

  const filter = useCall((v) => v.productCode !== productCode);
  const onService = useCall((params) => [{ ...params, isExemptions: '1' }]);
  const selectedKeys = useSimpleMemo((value ?? '').split(',').filter(Boolean));

  return (
    <SelectProduct
      title='选择产品'
      {...otherProps}
      rowKey='businessCode'
      selectedKeys={selectedKeys}
      selectType='checkbox'
      companyCode={companyCode}
      onService={onService}
      filter={filter}
      onOk={handleOk}
    >
      <Box className='pointer' onClick={handleClick}>
        <Input
          {...inputProps}
          className={clsx('pointer', inputProps.className)}
          readOnly
          value={value}
          addonAfter={<Icon type='table' />}
        />
      </Box>
    </SelectProduct>
  );
}

export default ExemptionsSelect;
